/*!
 * Copyright (C) 2020 - All Rights Reserved by
 * @author : ZhaoYanbo
 * @email  : zyb920@hotmail.com
 * @created: 2020-10-31
 * @version: 1.0.0.0
 *
 */

#include "CImgProvider.h"
#include <QPainter>
#include <QtCore>
#include <QtDebug>
#include "CPixmapCache.h"
#include "CScan.h"

#define ERROR_PNG ":/res/default.png"

const int width = 170;
const int height = 96;

CImgProvider::CImgProvider() : QQuickImageProvider(QQuickImageProvider::Pixmap)
{
    m_defaultPixmap.load(":/res/default.png");

    //初始化 读取json
    m_thumbPath = qApp->applicationDirPath() + "/thumb/";
    const QString dataFile = qApp->applicationDirPath() + "/data.json";

    QFile fi(dataFile);
    if(fi.open(QIODevice::ReadOnly))
    {
        QJsonParseError e;
        QJsonDocument jsonDoc = QJsonDocument::fromJson(fi.readAll(), &e);

        fi.close();

        if(e.error == QJsonParseError::NoError)
        {
            if(jsonDoc.isArray())
            {
                QJsonArray array = jsonDoc.array();
                for(int i=0; i<array.size(); ++i)
                {
                    QJsonObject obj = array.at(i).toObject();
                    QVariantHash hash = obj.toVariantHash();
                    thumbMap[hash["origin"].toString()] = hash["thumb"].toString();
                }
            }
        }
    }
}

CImgProvider::~CImgProvider()
{
    if(!m_bChanged)
        return;
    //保存
    QJsonArray array;
    QMapIterator<QString, QString> i(thumbMap);
    while (i.hasNext())
    {
        i.next();

        QJsonObject obj;
        obj.insert("origin", i.key());
        obj.insert("thumb",  i.value());

        array.append(obj);
    }
    QJsonDocument document;
    document.setArray(array);
    QByteArray byte_array = document.toJson(QJsonDocument::Compact);

    const QString dataFile = qApp->applicationDirPath() + "/data.json";
    QFile fi(dataFile);
    if(fi.open(QIODevice::WriteOnly | QIODevice::Truncate))
    {
        fi.write(byte_array);
        fi.flush();
        fi.close();
    }
}

QPixmap CImgProvider::requestPixmap(const QString &id, QSize *size, const QSize &/*requestedSize*/)
{
    if (size)
        *size = QSize(width, height);

    QPixmap pixmap;
    if(thumbMap.contains(id))//已经存在缩略图
    {
        QString value = thumbMap[id];
        if(!PixmapCache->find(value, pixmap))
        {
            pixmap.load( value );
            PixmapCache->insert(value, pixmap);
        }
    }
    else //不存在缩略图
    {
        QPixmap origin;
        origin.load(id);
        if( !origin.isNull() )
        {
            QPixmap pic(width, height);
            pic.fill(Qt::transparent);
            {
                QPainter p;
                p.begin(&pic);
                QPixmap tmpPic = origin.scaled(QSize(width, height), Qt::KeepAspectRatio, Qt::SmoothTransformation);

                p.drawPixmap((width - tmpPic.width())/2,
                             (height - tmpPic.height())/2,
                             tmpPic);
                p.end();
            }
            QString name = m_thumbPath + QString("%1.png").arg(thumbMap.size() + 1);
            if( pic.save(name) )
            {
                m_bChanged = true;
                thumbMap.insert(id, name);
                PixmapCache->insert(name, pic);
                pixmap = pic;
            }
        }
    }

    if( pixmap.isNull() )
        return m_defaultPixmap;

    return pixmap;
}
